/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aaron.platform.view;

import com.aaron.platform.dao.IXmlParser;
import com.aaron.platform.entity.ItscUserInfo;
import com.aaron.platform.exceptions.UserAlreadyExistException;
import com.aaron.platform.exceptions.UserNotExistException;
import com.aaron.platform.exceptions.UserSessionException;
import com.aaron.platform.exceptions.XmlParseException;
import com.aaron.platform.exceptions.XmlPathException;
import com.aaron.platform.service.IUserService;
import com.aaron.platform.service.UserSession;
import java.io.File;
import java.util.Date;
import java.util.logging.Level;
import javax.servlet.http.HttpSession;
import org.apache.commons.el.NullLiteral;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.myfaces.custom.tree2.TreeModel;

/**
 * 用户登陆backingbean
 * @author chenzhuohua
 */
public class UserloginBean {

    private static final Logger logger = Logger.getLogger(UserloginBean.class);

    /** 权限配置文件的目录 */
    private final static String CONFIG_PATH = "WEB-INF";

    /** menu file name */
    private final static String MENU_FILE_NAME = "menu.xml";
    
    /** default privilege ext value 0 */
    private final static Integer DEFAULT_EXTPRI_VALUE = 0;

    private String userName;
    
    private String userChName;

    private String password;

    private TreeModel treeModel;

    private IUserService userService;

    private IXmlParser xmlParser;

    private String oldPassword;

    private String newPassword;

    private String newPwdConfirm;

    public UserloginBean() {
        oldPassword = "";
        newPassword = "";
        newPwdConfirm = "";
    }

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public String getNewPwdConfirm() {
        return newPwdConfirm;
    }

    public void setNewPwdConfirm(String newPwdConfirm) {
        this.newPwdConfirm = newPwdConfirm;
    }

    public String getOldPassword() {
        return oldPassword;
    }

    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }


    public void setXmlParser(IXmlParser xmlParser) {
        this.xmlParser = xmlParser;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
    public String getUserChName() {
        if (StringUtils.isBlank(userChName)) {
            try {
                // 获取用户信息
                HttpSession httpSession = FacesUtil.getClientSession();
                UserSession userSession = (UserSession) httpSession.getAttribute("user");
                return userSession.getUserInfo().getUserChName();
            } catch (UserSessionException ex) {
                logger.error("Fail to get user session.");
                FacesUtil.addErrorMessage(null, ex.getErrorCode());
                return null;
            }
        } else {
            return userChName;
        }
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    /**
     * 用户登陆
     */
    public String userLogin() {

        // 不允许为空
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            FacesUtil.addErrorMessage(null, "er_userinfo_not_null");
            return null;
        }

        HttpSession session = null;
        ItscUserInfo userInfo = null;

        // 判断用户是否存在，密码是否正确
        try {
            userInfo = userService.findUserByName(userName);
            if (!password.equals(userInfo.getUserPwd())) {
                logger.error("user:" + userName + " gives a wrong password.");
                FacesUtil.addErrorMessage(null, "er_wrong_password");
                return null;
            }
            logger.info("user:" + userName + " login successfully.");
        } catch (UserNotExistException ex) {
            logger.error("user:" + userName + " does not exist.");
            FacesUtil.addErrorMessage(null, ex.getErrorCode(), userName);
            return null;
        }

        // 设置session属性
        UserSession userSession = new UserSession();
        userSession.setLoginTime(new Date());
        userSession.setUserInfo(userInfo);
        userSession.setIpAddress(FacesUtil.getClientIpAddress());
        String sessionId = null;
        try {
            session = FacesUtil.getClientSession();
            sessionId = session.getId();
        } catch (UserSessionException ex) {
            logger.error("Fail to get user(" + userName + ") session.");
                FacesUtil.addErrorMessage(null, ex.getErrorCode(), userName);
            return null;
        }
        userSession.setSessionId(sessionId);

        // 添加在线用户信息
        userService.addUserSession(userSession);

        // 添加seesion用户信息
        session.setAttribute("user", userSession);

        // 获取配置文件的路径
        String classPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        String xmlPath = classPath.substring(DEFAULT_EXTPRI_VALUE,
                classPath.indexOf(CONFIG_PATH) + 8);

        // 根据权限解释菜单文件
        String menuXmlPath = xmlPath + File.separator + MENU_FILE_NAME;
        File menuXml = new File(menuXmlPath);
        try {
            this.treeModel = xmlParser.parseMenuXml(menuXml, userInfo.getRoleInfo().getRoleName());
        } catch (XmlPathException ex) {
            logger.error("Fail to get menu xml file: " + menuXmlPath + ".");
            FacesUtil.addErrorMessage(null, ex.getErrorCode());
            return null;
        } catch (XmlParseException ex) {
            logger.error("Fail to parse menu xml file: " + menuXmlPath + ".");
            FacesUtil.addErrorMessage(null, ex.getErrorCode());
            return null;
        }

        FacesUtil.addInfoMessage(null, "in_login_success");
        return NavigationUrl.USER_LOGIN_SUCCEED;
    }

    /**
     * 用户当前用户信息
     * @return 用户信息
     */
    public ItscUserInfo getCurrentUserInfo() {
        String sessionId = null;
        try {
            HttpSession session = FacesUtil.getClientSession();
            sessionId = session.getId();
        } catch (UserSessionException ex) {
            logger.error("Fail to get user(" + userName + ") session.");
            FacesUtil.addErrorMessage(null, "er_get_user_session", userName);
            return null;
        }
        UserSession userSession = userService.getUserSession(sessionId);
        if (userSession == null) {
            logger.error("User(" + userName + ") session does not exist");
            FacesUtil.addErrorMessage(null, "er_get_user_session", userName);
            return null;
        }
        return userSession.getUserInfo();
    }

    /**
     * 用户注销
     */
    public String userLogout() {
        HttpSession session = null;
        userName = null;
        password = null;
        // 获取用户session
        try {
            session = FacesUtil.getClientSession();
        } catch (UserSessionException ex) {
            logger.error("Fail to get user(" + userName + ") session.");
            FacesUtil.addErrorMessage(null, "er_get_user_session", userName);
            return NavigationUrl.USER_LOGIN;
        }
        // 删除并清空用户会话信息
        userService.removeUserSession(session.getId());
        session.invalidate();

        // 返回登录界面
        return NavigationUrl.USER_LOGIN;
    }

    public boolean isLogin() {

        // 获取用户session
        HttpSession session = null;
        try {
            session = FacesUtil.getClientSession();
        } catch (UserSessionException ex) {
            logger.error("Fail to get user(" + userName + ") session.");
            return false;
        }
        UserSession userSession = userService.getUserSession(session.getId());
        return (userSession == null ? false : true);
    }

    public String pwdUpdate() {
        
        // 原始密码错误
        if (!password.equals(oldPassword)) {
            FacesUtil.addErrorMessage(null, "er_old_pwd_error");
            return null;
        }

        // 两次不一致
        if (!newPassword.equals(newPwdConfirm)) {
            FacesUtil.addErrorMessage(null, "er_pwd_dismatch");
            return null;
        }

        //修改密码
        ItscUserInfo currentUser = getCurrentUserInfo();
        currentUser.setUserPwd(newPassword);
        try {
            userService.updateUser(currentUser);

            // 修改成功，则更新userLoginBean中的密码
            password = newPassword;
            FacesUtil.addInfoMessage(null, "in_pwd_updated");
        } catch (UserNotExistException ex) {
            
            // 不成功，需要把sesssion中的密码重置
            currentUser.setUserPwd(oldPassword);
            logger.error("User (" + currentUser.getUserName() + ") has been removed when update its password!");
            FacesUtil.addErrorMessage(null, ex.getErrorCode(), currentUser.getUserName());
        } catch (UserAlreadyExistException ex) {

            // 只修改密码，这种情况不会发生
            currentUser.setUserPwd(oldPassword);
            logger.warn("User (" + currentUser.getUserName() + ") has already exist when update its password. But it will never happen.");
            FacesUtil.addErrorMessage(null, ex.getErrorCode(), currentUser.getUserName());
        }
        return null;
    }
    
    public boolean isManager() {
        ItscUserInfo userInfo = getCurrentUserInfo();
        return userInfo.getRoleInfo().getRoleName().equalsIgnoreCase("manager");
    }
    
    public boolean isNormal() {
        ItscUserInfo userInfo = getCurrentUserInfo();
        return userInfo.getRoleInfo().getRoleName().equalsIgnoreCase("normal");
    }
    
    public boolean isAdministrator() {
        ItscUserInfo userInfo = getCurrentUserInfo();
        return userInfo.getRoleInfo().getRoleName().equalsIgnoreCase("administrator");
    }

    public TreeModel getTreeModel() {
        return treeModel;
    }
}
